const axios = require('axios');

/**
 * AI分析API接口测试脚本
 * 测试新增的AI分析相关API端点
 */

// 配置
const BASE_URL = 'http://localhost:3129';
const TEST_TOKEN = 'your_jwt_token_here'; // 需要替换为实际的JWT token

// 创建axios实例
const api = axios.create({
  baseURL: BASE_URL,
  headers: {
    'Authorization': `Bearer ${TEST_TOKEN}`,
    'Content-Type': 'application/json'
  }
});

async function testStockAIAnalysisAPI() {
  console.log('📊 测试股票AI分析API...');
  
  try {
    const stockId = 1;
    const response = await api.get(`/api/stocks/ai-analysis/${stockId}?refresh=true`);
    
    console.log('✅ 股票AI分析API调用成功');
    console.log('📈 响应状态:', response.status);
    console.log('📊 分析结果:', {
      overallScore: response.data.data.overallScore,
      riskLevel: response.data.data.riskLevel,
      confidenceLevel: response.data.data.confidenceLevel,
      investmentAdvicePreview: response.data.data.investmentAdvice.substring(0, 50) + '...'
    });
    
    return true;
  } catch (error) {
    console.error('❌ 股票AI分析API测试失败:', error.response?.data || error.message);
    return false;
  }
}

async function testCategoryAIAnalysisAPI() {
  console.log('\n🏢 测试大分类AI分析API...');
  
  try {
    const categoryKey = 'a_stock';
    const response = await api.get(`/api/stocks/category-ai-analysis/${categoryKey}?refresh=true`);
    
    console.log('✅ 大分类AI分析API调用成功');
    console.log('📊 响应状态:', response.status);
    console.log('🏢 分析结果:', {
      marketScore: response.data.data.marketScore,
      trendDirection: response.data.data.trendDirection,
      hotSectors: response.data.data.hotSectors.slice(0, 2),
      strategyPreview: response.data.data.investmentStrategy.substring(0, 50) + '...'
    });
    
    return true;
  } catch (error) {
    console.error('❌ 大分类AI分析API测试失败:', error.response?.data || error.message);
    return false;
  }
}

async function testBatchStockAnalysisAPI() {
  console.log('\n🔄 测试批量股票AI分析API...');
  
  try {
    const stockIds = [1, 2, 3]; // 测试前3个股票
    const response = await api.post('/api/stocks/batch-ai-analysis', {
      stockIds: stockIds
    });
    
    console.log('✅ 批量股票AI分析API调用成功');
    console.log('📊 响应状态:', response.status);
    console.log('📈 批量结果:', response.data.data);
    
    return true;
  } catch (error) {
    console.error('❌ 批量股票AI分析API测试失败:', error.response?.data || error.message);
    return false;
  }
}

async function testBatchCategoryAnalysisAPI() {
  console.log('\n🔄 测试批量大分类AI分析API...');
  
  try {
    const response = await api.post('/api/stocks/batch-category-ai-analysis');
    
    console.log('✅ 批量大分类AI分析API调用成功');
    console.log('📊 响应状态:', response.status);
    console.log('🏢 批量结果:', response.data.data);
    
    return true;
  } catch (error) {
    console.error('❌ 批量大分类AI分析API测试失败:', error.response?.data || error.message);
    return false;
  }
}

async function testHealthCheck() {
  console.log('🏥 测试服务健康检查...');
  
  try {
    const response = await axios.get(`${BASE_URL}/health`);
    console.log('✅ 服务健康检查通过');
    console.log('💚 服务状态:', response.status);
    return true;
  } catch (error) {
    console.error('❌ 服务健康检查失败:', error.message);
    return false;
  }
}

async function runAPITests() {
  console.log('🚀 开始AI分析API测试\n');
  
  // 检查JWT token是否设置
  if (TEST_TOKEN === 'your_jwt_token_here') {
    console.log('⚠️  警告: 请先设置有效的JWT token');
    console.log('💡 提示: 修改脚本中的 TEST_TOKEN 变量');
    console.log('🔑 获取token: 请先通过登录API获取有效的JWT token\n');
  }
  
  const results = {
    health: false,
    stockAnalysis: false,
    categoryAnalysis: false,
    batchStock: false,
    batchCategory: false,
  };
  
  // 1. 健康检查
  results.health = await testHealthCheck();
  
  if (!results.health) {
    console.log('\n❌ 服务未启动或不可访问，请先启动服务');
    console.log('💡 启动命令: pnpm run dev');
    return;
  }
  
  // 2. 单个股票AI分析
  results.stockAnalysis = await testStockAIAnalysisAPI();
  
  // 3. 大分类AI分析
  results.categoryAnalysis = await testCategoryAIAnalysisAPI();
  
  // 4. 批量股票分析
  results.batchStock = await testBatchStockAnalysisAPI();
  
  // 5. 批量大分类分析
  results.batchCategory = await testBatchCategoryAnalysisAPI();
  
  // 输出测试总结
  console.log('\n📋 API测试结果总结:');
  console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
  console.log(`🏥 健康检查:         ${results.health ? '✅ 通过' : '❌ 失败'}`);
  console.log(`📊 股票AI分析:       ${results.stockAnalysis ? '✅ 通过' : '❌ 失败'}`);
  console.log(`🏢 大分类AI分析:     ${results.categoryAnalysis ? '✅ 通过' : '❌ 失败'}`);
  console.log(`🔄 批量股票分析:     ${results.batchStock ? '✅ 通过' : '❌ 失败'}`);
  console.log(`🔄 批量大分类分析:   ${results.batchCategory ? '✅ 通过' : '❌ 失败'}`);
  
  const passedTests = Object.values(results).filter(Boolean).length;
  const totalTests = Object.keys(results).length;
  
  console.log(`\n🎯 总体结果: ${passedTests}/${totalTests} 项API测试通过`);
  
  if (passedTests === totalTests) {
    console.log('🎉 所有API测试通过！');
  } else if (passedTests > 1) {
    console.log('⚠️  部分API测试失败，请检查相关配置');
  } else {
    console.log('❌ 大部分API测试失败，请检查服务状态和配置');
  }
  
  console.log('\n📚 可用的API端点:');
  console.log('• GET  /api/stocks/ai-analysis/{stockId}');
  console.log('• GET  /api/stocks/category-ai-analysis/{categoryKey}');
  console.log('• POST /api/stocks/batch-ai-analysis');
  console.log('• POST /api/stocks/batch-category-ai-analysis');
}

// 运行测试
runAPITests()
  .then(() => {
    console.log('\nAPI测试完成');
    process.exit(0);
  })
  .catch((error) => {
    console.error('\nAPI测试过程中发生错误:', error);
    process.exit(1);
  });